<?php

namespace app\admin\controller;

use app\admin\common\Common;
use app\admin\model\UserModel;
use app\admin\validate\UserValidate;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Request;

class User extends LoginThere
{
    public function index(){
        try {
            $listUser = Db::name('user')
                ->alias('u')
                ->join('app a', 'a.appid = u.appid')
                ->field('u.*,a.appname')
                ->paginate(10);
        } catch (DbException $e) {
             return Common::result(400,$e->getMessage());
        }
        $page = $listUser->render();
        return $this->fetch('/user/index', ['list' => $listUser, 'page' => $page]);
    }

    /**
     *获取用户
     */
    public function queryuser($id){
        try {
            $listUser = Db::name('user')->where('id', $id)->find();
            return $this->fetch('user/queryuser')->assign('user',$listUser);
        } catch (DataNotFoundException $e) {
             return Common::result(400,$e->getMessage());
        } catch (ModelNotFoundException $e) {
             return Common::result(400,$e->getMessage());
        } catch (DbException $e) {
             return Common::result(400,$e->getMessage());
        }
    }
    /**
     *编辑用户
     */
    public function updateuser(Request $request){
        $data = $request->post();
        $validate = new UserValidate();
        if (!$validate->scene('updateuser')->check($data)) {
            return Common::result(400,$validate->getError());
        }
        return UserModel::updateuser($data);
    }

    /**
     * 添加用户
     */
    public function adduser(Request  $request){
        $data = $request->post();
        $validate = new UserValidate();
        if (!$validate->scene('adduser')->check($data)){
            return Common::result(400,$validate->getError());
        }
        return UserModel::adduser($data);
    }

    /**
     * 删除app
     */
    public function deluser(Request $request){
        $data = $request->post();
        return UserModel::deluser($data);
    }

    public function searchuser(Request $request){
        if (!empty($data['searchusername'])){
            return Common::result(400,"请输入完整");
        }
        $data = $request->post();
        return UserModel::searchuser($data);
    }


}